package com.xiaoshuidi.cloud.module.bpm.job.xxljob;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
@RequiredArgsConstructor
public class HistoriesTicketDataProcessJob {

    @XxlJob("ticket-data-process")
    @TenantIgnore
    public void ticketDataProcess(){
        log.info("[审批工单历史数据补充]-----开始-----");
        List<Map<String, Object>> maps = SqlRunner.db().selectList("SELECT\n" +
                "\tarv.ID_ AS arvID,\n" +
                "\tarv.REV_ AS arvREV,\n" +
                "\tarv.EXECUTION_ID_ AS arvEXECUTION_ID_,\n" +
                "\tarv.PROC_INST_ID_ AS arvPROC_INST_ID_,\n" +
                "\tagb.ID_ AS agbID,\n" +
                "\tagb.BYTES_ AS BYTES_ \n" +
                "FROM\n" +
                "\tact_ru_variable arv\n" +
                "\tLEFT JOIN act_ge_bytearray agb ON arv.BYTEARRAY_ID_ = agb.ID_ \n" +
                "WHERE\n" +
                "\tarv.TYPE_ = \"serializable\";");
        maps.stream().forEach(map -> {
            byte[] serializedData = (byte[]) map.get("BYTES_");
            String arvRev = map.get("arvREV").toString();
            String arvEXECUTIONId = map.get("arvEXECUTION_ID_").toString();
            String arvPROCInstId = map.get("arvPROC_INST_ID_").toString();
            // 将字节流转换为对象
            try (ByteArrayInputStream byteStream = new ByteArrayInputStream(serializedData); ObjectInputStream objectStream = new ObjectInputStream(byteStream)){
                Object deserializedObject = objectStream.readObject();
                if(deserializedObject instanceof BpmProcessInstanceCreateReqDTO.ExtendDto){
                    Map<String, Object> stringObjectMap = BeanUtil.beanToMap(deserializedObject);

                    Set<Map.Entry<String, Object>> entries = stringObjectMap.entrySet();
                    // 插入一条数据
                    StringBuilder sb = new StringBuilder();
                    sb.append("INSERT INTO act_ru_variable(ID_, REV_, TYPE_, NAME_,EXECUTION_ID_, PROC_INST_ID_,TEXT_) VALUES ");
                    for (Map.Entry<String, Object> entry : entries) {
                        if("roomName, customName, customPhone".contains(entry.getKey())){
                            String key = entry.getKey();
                            if(key.equals("customName")){
                                key = "customerName";
                            } else if (key.equals("customPhone")) {
                                key = "customerPhone";
                            }
                            sb.append("(");
                            sb.append("\"" + IdUtil.getSnowflakeNextId() + "\",");
                            sb.append(arvRev + ",");
                            sb.append("\"string\",");
                            sb.append("\"" + key + "\",");
                            sb.append("\"" + arvEXECUTIONId + "\",");
                            sb.append("\"" + arvPROCInstId + "\",");
                            sb.append("\"" + stringObjectMap.get(entry.getKey()) + "\"");
                            sb.append(")");
                            sb.append(",");
                        }
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    log.info("sql语句:{}", sb.toString());
                    SqlRunner.db().insert(sb.toString());
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        log.info("[审批工单历史数据补充]-----完成-----");
    }
}
